import 'dart:io';

import 'package:dart_bean/config/config.dart';
import 'package:dart_bean/generator.dart';
import 'package:dart_bean/util/error_tip.dart';
import 'package:test/test.dart';

final projectRoot = Directory('').parent;
final toDir = Directory('test_bean_lib');

Future<void> startMain() async {
  await Generator.startMain(['--projectDir', projectRoot.path, '--libDir', toDir.path]);
}

void prepareTestBeans(Directory fromDir, Directory toDir) {
  if (toDir.existsSync()) toDir.deleteSync(recursive: true);
  fromDir.listSync(recursive: true).forEach((e) {
    final path = e.path.replaceFirst(fromDir.path, '');
    if (path.endsWith('.dart')) {
      final file = File('${toDir.path}$path');
      if (!file.parent.existsSync()) file.parent.createSync(recursive: true);
      file.writeAsStringSync(File(e.path).readAsStringSync());
    }
  });
}

void main() async {
  Generator.config = parseConfig(Directory('test').parent);
  Generator.testMode = true;
  final folder = 'test_case';

  test('unsupported_json_key_feature', () async {
    prepareTestBeans(Directory('$folder/unsupported_json_key_feature'), toDir);
    try {
      await startMain();
      throw 'no error found';
    } catch (e) {
      final msg = e.toString();
      expect(msg.contains(unsupportedJsonKeyFeatureError), true);
    }
  });

  test('unsupported_var_type_name', () async {
    prepareTestBeans(Directory('$folder/unsupported_var_type_name'), toDir);
    try {
      await startMain();
      throw 'no error found';
    } catch (e) {
      final msg = e.toString();
      expect(msg.contains(unsupportedVarTypeNameError), true);
    }
  });

  test('unsupported_type_alise', () async {
    prepareTestBeans(Directory('$folder/unsupported_type_alise'), toDir);
    try {
      await startMain();
      throw 'no error found';
    } catch (e) {
      final msg = e.toString();
      expect(msg.contains(unsupportedTypeAliseError), true);
    }
  });

  test('unsupported_map_generic', () async {
    prepareTestBeans(Directory('$folder/unsupported_map_generic'), toDir);
    try {
      await startMain();
      throw 'no error found';
    } catch (e) {
      final msg = e.toString();
      expect(msg.contains(unsupportedMapFieldError), true);
    }
  });

  test('ok', () async {
    Generator.config.autoDefaultValueStyle = true;
    prepareTestBeans(Directory('$folder/ok'), toDir);
    await startMain();
  });
}
